<?php
/**
 * @author: justwkj
 * @date: 2020/4/20 10:37
 * @email: justwkj@gmail.com
 * @desc:
 */

function help() {
    $url  = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/index.php';
    echo "请求有误!格式如下:<br/>";
    echo $url. "?from=gitee&project=blog";
    echo '<br>';
    echo $url."?from=github&project=blog";
    http_response_code(404);
    die();
}

if (!isset($_GET['from'])) {
    help();
}
$from = $_GET['from'];
if (!isset($_GET['project'])) {
    help();
}
$project = $_GET['project'];

$hookConf = file_get_contents('./hook.json');
$hookConf = json_decode($hookConf, true);
if (!$hookConf) {
    echo 'hook.json 文件有误!';
    die;
}


$hookData = [];
foreach ($hookConf as $hook) {
    if ($hook['from'] == $from && $hook['project'] == $project) {
        $hookData = $hook;
        break;
    }
}
if (!$hookData) {
    echo '参数有误!';
    die;
}

$secret = $hookData['token'];
if ($hookData['from'] === 'github') {
    if ($signature = $_SERVER['HTTP_X_HUB_SIGNATURE']) {
        $hash = "sha1=" . hash_hmac('sha1', $HTTP_RAW_POST_DATA, $secret);
        $hash = "sha1=" . hash_hmac('sha1', file_get_contents('php://input'), $secret);
        if (strcmp($signature, $hash) == 0) {
            shell_exec($hookData['scripts']);
            echo 'ok';
            exit();
        }
    }
} else if ($hookData['from'] === 'gitee') {
    if ($_SERVER['HTTP_X_GITEE_TOKEN'] === $secret) {
        shell_exec($hookData['scripts']);
        echo 'ok';
        exit();
    }
}


echo "签名有误!";
http_response_code(404);



